package cn.rkylin.oms.common.annotation.aspect;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.system.log.dao.ILogDao;

@Aspect
@Component
public class SystemLogAspect {
    @Autowired
    private LogUtil logUtil;
	@Autowired
	private ILogDao logDao;

    private static final Log logger = LogFactory.getLog(SystemLogAspect.class);

    /*
     * 后置拦截
     */
    @AfterReturning(returning = "returnObj",pointcut = "@annotation(cn.rkylin.oms.common.annotation.SystemControllerLog)")
    public void doBefore(JoinPoint joinPoint,Map<String, Object> returnObj){
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession session = request.getSession();
//        // 获取当前用户信息
//        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
//        // 请求的IP
//        String ip = request.getRemoteAddr();
//
//        String methodName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";
        try {
//            String methodDescription =getMethodDescription(joinPoint);
//            String params = "";
//            if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {
//                for ( int i = 0; i < joinPoint.getArgs().length; i++) {
//                    params += JSONUtils.toJSONString(joinPoint.getArgs()[i]) + ";";
//                }
//            }
            String mthdName = joinPoint.getSignature().getName();
            Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
            Method method = joinPoint.getTarget().getClass().getMethod(mthdName,parameterTypes);
            String moduleName = method.getAnnotation(SystemControllerLog.class).module();
            String operationName = method.getAnnotation(SystemControllerLog.class).operation();
            String primaryCodeName = method.getAnnotation(SystemControllerLog.class).keyCode();

            String returnMessage = (String)returnObj.get("msg");
            String result = (String)returnObj.get("result");
            String primaryCode = "result";
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if(StringUtils.isNotEmpty(primaryCodeName)){
            	Object obj = returnObj.get(primaryCodeName);
            	if (obj.getClass().isArray()) {
            		String[] obs = (String[])returnObj.get(primaryCodeName);
            		for (String ob : obs) {
                        if("failed".equals(result)){
                            logUtil.trace(new DBLog(ob,operationName,moduleName,"[失败]"+returnMessage),logDao,currentUser.getFullName());
                        }else{
                            logUtil.trace(new DBLog(ob,operationName,moduleName,"[成功]"+returnMessage),logDao,currentUser.getFullName());
                        }
					}
            	}else {
                    primaryCode = (String)returnObj.get(primaryCodeName);
                    if("failed".equals(result)){
                        logUtil.trace(new DBLog(primaryCode,operationName,moduleName,"[失败]"+returnMessage),logDao,currentUser.getFullName());
                    }else{
                        logUtil.trace(new DBLog(primaryCode,operationName,moduleName,"[成功]"+returnMessage),logDao,currentUser.getFullName());
                    }
            	}
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getMethodDescription(JoinPoint joinPoint) throws Exception{
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    SystemControllerLog annotation = method.getAnnotation(SystemControllerLog.class);
                    description = annotation.module()+"|"+annotation.operation();
                    break;
                }
            }
        }
        return description;
    }
}
